﻿using System.Collections.Generic;
using System.IO;

public class CJFFile
{
    private const int DocumentTypeIndex = 0;
    private const int DocumentNameIndex = 1;
    private const int DocumentBodyIndex = 2;

    public static CJFFile Create(string fileContent)
    {
        string[] jsonLines = fileContent.Split('\n');

        Dictionary<string, SimpleJson.JsonArray> contentDictionary = new Dictionary<string, SimpleJson.JsonArray>();
        List<string> contentKeyList = new List<string>();

        if (!string.IsNullOrEmpty(jsonLines[DocumentTypeIndex]))
        {
            SimpleJson.JsonArray rowJsonArray = SimpleJson.SimpleJson.DeserializeObject(jsonLines[DocumentTypeIndex]) as SimpleJson.JsonArray;
            contentDictionary.Add(rowJsonArray[0] as string, rowJsonArray);
        }

        if (!string.IsNullOrEmpty(jsonLines[DocumentNameIndex]))
        {
            SimpleJson.JsonArray rowJsonArray = SimpleJson.SimpleJson.DeserializeObject(jsonLines[DocumentNameIndex]) as SimpleJson.JsonArray;
            contentDictionary.Add(rowJsonArray[0] as string, rowJsonArray);
        }

        for (int i = DocumentBodyIndex; i < jsonLines.Length; ++i)
        {
            if (!string.IsNullOrEmpty(jsonLines[i]))
            {
                SimpleJson.JsonArray rowJsonArray = SimpleJson.SimpleJson.DeserializeObject(jsonLines[i]) as SimpleJson.JsonArray;
                contentDictionary.Add(rowJsonArray[0] as string, rowJsonArray);
                contentKeyList.Add(rowJsonArray[0] as string);
            }
        }

        CJFFile cjfFile = new CJFFile();
        cjfFile.contentDictionary = contentDictionary;
        cjfFile.contentKeyList = contentKeyList;

        return cjfFile;
    }

    public static string LoadFile(string pathFilename)
    {
        StreamReader reader = new StreamReader(pathFilename);
        string fileContent = reader.ReadToEnd();
        reader.Close();
        reader.Dispose();

        return fileContent;
    }

    private Dictionary<string, SimpleJson.JsonArray> contentDictionary;
    private List<string> contentKeyList;

    private CJFFile()
    {

    }

    public string GetCellContent(int id, int column)
    {
        string idString = id.ToString();
        if (contentDictionary.ContainsKey(idString) && contentDictionary[idString].Count > column)
        {
            return contentDictionary[idString][column] as string;
        }

        return string.Empty;
    }

    public int GetDocumentBodyLength()
    {
        return contentKeyList.Count;
    }

    public List<string> GetContentKeyList()
    {
        return contentKeyList;
    }
}
